package com.candy.candylogservice.interceptor;

import com.candy.candycommon.utils.HttpServletUtils;
import com.candy.candylogservice.dto.LogLinkDTO;
import com.gitee.candy.constant.ConstantUtils;
import com.gitee.candy.number.SnowflakeIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @author suYanLong
 * @date 2022年10月25日 15:51
 */
@Slf4j
public class LogUtils {

    public static ThreadLocal<LogLinkDTO> threadLocalLog = new ThreadLocal<>();

    public static Long getTraceId() {
        HttpServletRequest request = HttpServletUtils.getRequest();
        if (!StringUtils.isEmpty(request.getHeader(ConstantUtils.TRACE_ID))) {
            log.info("request 中存在traceId" + request.getHeader(ConstantUtils.TRACE_ID));
            MDC.put(ConstantUtils.TRACE_ID, request.getHeader(ConstantUtils.TRACE_ID));
        }

        if (!Optional.ofNullable(MDC.get(ConstantUtils.TRACE_ID)).isPresent()) {
            SnowflakeIdGenerator snowflakeIdGenerator = new SnowflakeIdGenerator(1, 1);
            MDC.put(ConstantUtils.TRACE_ID, snowflakeIdGenerator.nextId() + "");
            log.info("MDC 不存在traceId 重新生产 " + MDC.get(ConstantUtils.TRACE_ID));
        }
        return Long.valueOf(MDC.get(ConstantUtils.TRACE_ID));
    }

    public static void clear() {
        threadLocalLog.remove();
        MDC.clear();
    }

    public static boolean setLog(LogLinkDTO logLinkDTO) {
        threadLocalLog.set(logLinkDTO);
        return true;
    }

    public static LogLinkDTO getLog() {
        return threadLocalLog.get();
    }

}
